import os
import json
import glob
import re
def get_all_files(directory,extention):
    """
    Get all files in a directory with a specific extention
    Args:
    directory (str): The directory to search for files.
    extention (str): The extention of the file to search for.
    Returns:
    list: A list of files with the specified extention in the directory.
    """
    if not os.path.exists(directory):
        print(f"Error: Directory '{directory}' does not exist.")
        return []
    file_pattern = os.path.join(directory, f"*.{extention}")
    files = glob.glob(file_pattern)
    if not files:
        print(f"No matching files found in directory '{directory}'.")
        return []
    return files

def read_file_for_extention(file_path):
    extracted_content = {}
    with open(file_path, 'r', encoding='utf-8') as file:
        for idx,line in enumerate(file):
            match = re.search(r'cppfile.*\.cc', line)
            if match:
                filename = os.path.basename(file_path)
                codeline = match.group()
                match = re.search(r'cppfile\[firstline=(\d+),lastline=(\d+)\]', codeline)
                if match:
                    firstline = match.group(1)
                    lastline = match.group(2)
                    # Extract the specific part of the file path
                    name = codeline.split('/')[-1]
                    extracted_content[name] = {'firstline': eval(firstline), 'lastline': eval(lastline), 'file_name': name,'line':idx+1}
    return extracted_content

def all_info_to_json(file_paths,out_json):
    info = {}
    for filename in file_paths:
        extracted_content = read_file_for_extention(filename)
        info[filename] = extracted_content
    with open(out_json, 'w') as f:
        json.dump(info, f, indent=4)

def read_json_to_sed_command(json_file,script_file):
    with open(json_file,'r') as f:
        json_data = json.load(f)
    with open(script_file,'w') as f:
        f.write("#!/bin/bash\n")
        for filename in json_data:
            for cpp_file_name in json_data[filename].items():
                firstline = cpp_file_name[1]['firstline']
                lastline = cpp_file_name[1]['lastline']
                line = cpp_file_name[1]['line']
                filename = f"sed -i '{line}s/\\(firstline=\\)[^,]*/\\1{firstline}/; {line}s/\\(lastline=\\)[^,]*/\\1{lastline}/' {filename}\n"
                f.write(filename)



if __name__ == "__main__":
    directory = "/home/liushuai/arithmetic/contents"
    files = get_all_files(directory, "tex")
    extract_file = "extracted_content.json"
    # res = read_file_for_extention(files[-2])
    all_info_to_json(files, extract_file)
    read_json_to_sed_command(extract_file, "run.sh")


